import 'package:dio/dio.dart';
import '../utils/auth_interceptor.dart';

class ApiClient {
  static const String baseUrl = 'http://localhost:8080';
  late final Dio _dio;
  AuthInterceptor? _authInterceptor;

  static final ApiClient _instance = ApiClient._internal();
  factory ApiClient() => _instance;

  ApiClient._internal() {
    _dio = Dio(BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(seconds: 5),  // 减少连接超时
      receiveTimeout: const Duration(seconds: 10), // 减少接收超时
      headers: {
        'Content-Type': 'application/json',
      },
    ));

    // 启用详细的API日志
    _dio.interceptors.add(LogInterceptor(
      requestBody: true,   // 显示请求体
      responseBody: true,  // 显示响应体
      requestHeader: true, // 显示请求头
      responseHeader: true, // 显示响应头
      error: true,
      logPrint: (obj) => print('🌐 [API LOG] $obj'),
    ));

    // 添加自定义拦截器用于更详细的日志
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        print('📤 [API REQUEST] ${options.method} ${options.uri}');
        if (options.queryParameters.isNotEmpty) {
          print('📝 [QUERY PARAMS] ${options.queryParameters}');
        }
        if (options.data != null) {
          print('📄 [REQUEST DATA] ${options.data}');
        }
        handler.next(options);
      },
      onResponse: (response, handler) {
        print('📥 [API RESPONSE] ${response.statusCode} ${response.statusMessage}');
        print('✅ [RESPONSE DATA] ${response.data}');
        handler.next(response);
      },
      onError: (error, handler) {
        print('❌ [API ERROR] ${error.type}: ${error.message}');
        if (error.response != null) {
          print('💥 [ERROR RESPONSE] Status: ${error.response?.statusCode}, Data: ${error.response?.data}');
        }
        handler.next(error);
      },
    ));
  }

  /// 设置认证拦截器
  void setAuthInterceptor(AuthInterceptor authInterceptor) {
    // 移除旧的认证拦截器
    if (_authInterceptor != null) {
      _dio.interceptors.remove(_authInterceptor);
    }
    
    // 添加新的认证拦截器
    _authInterceptor = authInterceptor;
    _dio.interceptors.add(_authInterceptor!);
    
    print('🔑 [API_CLIENT] 认证拦截器已设置');
  }

  /// 移除认证拦截器
  void removeAuthInterceptor() {
    if (_authInterceptor != null) {
      _dio.interceptors.remove(_authInterceptor);
      _authInterceptor = null;
      print('🔓 [API_CLIENT] 认证拦截器已移除');
    }
  }

  Dio get dio => _dio;

  Future<Response<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) async {
    return await _dio.get<T>(
      path,
      queryParameters: queryParameters,
      options: options,
    );
  }

  Future<Response<T>> post<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) async {
    return await _dio.post<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
    );
  }

  Future<Response<T>> put<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) async {
    return await _dio.put<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
    );
  }

  Future<Response<T>> delete<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
  }) async {
    return await _dio.delete<T>(
      path,
      data: data,
      queryParameters: queryParameters,
      options: options,
    );
  }
}